<template>
  <div class="patient-dashboard">
    <h1>Patient Dashboard</h1>
    
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="welcome-card">
          <template #header>
            <div class="card-header">
              <span>Welcome Back, {{ userInfo.name }}</span>
            </div>
          </template>
          <div class="welcome-content">
            <p>Your next appointment is on <strong>{{ formatDate(nextAppointment.date) }}</strong> at <strong>{{ nextAppointment.time }}</strong> with <strong>{{ nextAppointment.doctorName }}</strong>.</p>
            <p class="health-tip">Health Tip: {{ healthTip }}</p>
            <div class="action-buttons">
              <el-button type="primary" @click="bookAppointment">Book New Appointment</el-button>
              <el-button type="info" @click="viewMedicalRecords">View Medical Records</el-button>
            </div>
          </div>
        </el-card>
        
        <el-card class="upcoming-appointments-card">
          <template #header>
            <div class="card-header">
              <span>Upcoming Appointments</span>
              <el-button class="button" text>View All</el-button>
            </div>
          </template>
          <div v-if="upcomingAppointments.length">
            <el-table :data="upcomingAppointments" style="width: 100%">
              <el-table-column prop="date" label="Date" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.date) }}
                </template>
              </el-table-column>
              <el-table-column prop="time" label="Time" width="100" />
              <el-table-column prop="doctorName" label="Doctor" />
              <el-table-column prop="department" label="Department" />
              <el-table-column prop="status" label="Status" width="120">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="Actions" width="180">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    :disabled="scope.row.status !== 'Confirmed'"
                    type="danger" 
                    @click="cancelAppointment(scope.row)"
                  >
                    Cancel
                  </el-button>
                  <el-button 
                    size="small" 
                    :disabled="scope.row.status !== 'Confirmed'"
                    @click="rescheduleAppointment(scope.row)"
                  >
                    Reschedule
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="No upcoming appointments" />
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>My Profile</span>
              <el-button class="button" text @click="editProfile">Edit</el-button>
            </div>
          </template>
          <div class="profile-content">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar">
                {{ userInfo.name.charAt(0) }}
              </el-avatar>
            </div>
            <el-descriptions :column="1" border class="profile-details">
              <el-descriptions-item label="Name">{{ userInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="Gender">{{ userInfo.gender === 1 ? 'Male' : 'Female' }}</el-descriptions-item>
              <el-descriptions-item label="Date of Birth">{{ formatDate(userInfo.birthDate) }}</el-descriptions-item>
              <el-descriptions-item label="Phone">{{ userInfo.phone }}</el-descriptions-item>
              <el-descriptions-item label="Email">{{ userInfo.email }}</el-descriptions-item>
              <el-descriptions-item label="Address">{{ userInfo.address }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>Quick Actions</span>
            </div>
          </template>
          <div class="quick-actions-content">
            <el-button type="primary" icon="el-icon-message" plain @click="contactDoctor">
              Contact Doctor
            </el-button>
            <el-button type="success" icon="el-icon-document" plain @click="viewPrescriptions">
              View Prescriptions
            </el-button>
            <el-button type="warning" icon="el-icon-bell" plain @click="setReminders">
              Set Medication Reminders
            </el-button>
            <el-button type="info" icon="el-icon-document-copy" plain @click="requestRecords">
              Request Medical Records
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="recent-prescriptions-card">
          <template #header>
            <div class="card-header">
              <span>Recent Prescriptions</span>
              <el-button class="button" text>View All</el-button>
            </div>
          </template>
          <div v-if="recentPrescriptions.length">
            <el-table :data="recentPrescriptions" style="width: 100%">
              <el-table-column prop="date" label="Date" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.date) }}
                </template>
              </el-table-column>
              <el-table-column prop="medication" label="Medication" />
              <el-table-column prop="dosage" label="Dosage" width="150" />
              <el-table-column prop="doctor" label="Prescribed By" width="150" />
              <el-table-column width="80">
                <template #default="scope">
                  <el-button type="primary" link @click="viewPrescriptionDetails(scope.row)">
                    Details
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="No recent prescriptions" />
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="recent-tests-card">
          <template #header>
            <div class="card-header">
              <span>Recent Medical Tests</span>
              <el-button class="button" text>View All</el-button>
            </div>
          </template>
          <div v-if="recentTests.length">
            <el-table :data="recentTests" style="width: 100%">
              <el-table-column prop="date" label="Date" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.date) }}
                </template>
              </el-table-column>
              <el-table-column prop="test" label="Test" />
              <el-table-column prop="result" label="Result" width="100">
                <template #default="scope">
                  <el-tag :type="getResultType(scope.row.result)">
                    {{ scope.row.result }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="doctor" label="Referred By" width="150" />
              <el-table-column width="80">
                <template #default="scope">
                  <el-button type="primary" link @click="viewTestDetails(scope.row)">
                    Details
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="No recent medical tests" />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- Book Appointment Dialog -->
    <el-dialog
      v-model="appointmentDialogVisible"
      title="Book New Appointment"
      width="50%"
    >
      <el-form ref="appointmentForm" :model="appointmentForm" :rules="appointmentRules" label-width="120px">
        <el-form-item label="Department" prop="department">
          <el-select v-model="appointmentForm.department" placeholder="Select department" style="width: 100%">
            <el-option label="Cardiology" value="Cardiology" />
            <el-option label="Dermatology" value="Dermatology" />
            <el-option label="Neurology" value="Neurology" />
            <el-option label="Orthopedics" value="Orthopedics" />
            <el-option label="Pediatrics" value="Pediatrics" />
            <el-option label="Psychiatry" value="Psychiatry" />
          </el-select>
        </el-form-item>
        <el-form-item label="Doctor" prop="doctorId">
          <el-select v-model="appointmentForm.doctorId" placeholder="Select doctor" style="width: 100%">
            <el-option
              v-for="doctor in doctorOptions"
              :key="doctor.id"
              :label="doctor.name"
              :value="doctor.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Date" prop="date">
          <el-date-picker
            v-model="appointmentForm.date"
            type="date"
            placeholder="Select date"
            style="width: 100%"
            :disabled-date="disablePastDates"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="Time" prop="time">
          <el-select v-model="appointmentForm.time" placeholder="Select time slot" style="width: 100%">
            <el-option
              v-for="slot in availableTimeSlots"
              :key="slot.value"
              :label="slot.label"
              :value="slot.value"
              :disabled="slot.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Reason" prop="reason">
          <el-input v-model="appointmentForm.reason" type="textarea" :rows="3" placeholder="Briefly describe your symptoms or reason for visit" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="appointmentDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitAppointment">Book</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- Edit Profile Dialog -->
    <el-dialog
      v-model="profileDialogVisible"
      title="Edit Profile"
      width="50%"
    >
      <el-form ref="profileForm" :model="profileForm" :rules="profileRules" label-width="120px">
        <el-form-item label="Name" prop="name">
          <el-input v-model="profileForm.name" />
        </el-form-item>
        <el-form-item label="Phone" prop="phone">
          <el-input v-model="profileForm.phone" />
        </el-form-item>
        <el-form-item label="Email" prop="email">
          <el-input v-model="profileForm.email" />
        </el-form-item>
        <el-form-item label="Address" prop="address">
          <el-input v-model="profileForm.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="profileDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="saveProfile">Save</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- Prescription Details Dialog -->
    <el-dialog
      v-model="prescriptionDetailDialogVisible"
      title="Prescription Details"
      width="50%"
    >
      <div v-if="selectedPrescription.id">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="Date">{{ formatDate(selectedPrescription.date) }}</el-descriptions-item>
          <el-descriptions-item label="Medication">{{ selectedPrescription.medication }}</el-descriptions-item>
          <el-descriptions-item label="Dosage">{{ selectedPrescription.dosage }}</el-descriptions-item>
          <el-descriptions-item label="Instructions">{{ selectedPrescription.instructions }}</el-descriptions-item>
          <el-descriptions-item label="Duration">{{ selectedPrescription.duration }}</el-descriptions-item>
          <el-descriptions-item label="Prescribed By">{{ selectedPrescription.doctor }}</el-descriptions-item>
          <el-descriptions-item label="Notes">{{ selectedPrescription.notes || 'N/A' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    
    <!-- Test Details Dialog -->
    <el-dialog
      v-model="testDetailDialogVisible"
      title="Test Details"
      width="50%"
    >
      <div v-if="selectedTest.id">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="Date">{{ formatDate(selectedTest.date) }}</el-descriptions-item>
          <el-descriptions-item label="Test">{{ selectedTest.test }}</el-descriptions-item>
          <el-descriptions-item label="Result">
            <el-tag :type="getResultType(selectedTest.result)">{{ selectedTest.result }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Referred By">{{ selectedTest.doctor }}</el-descriptions-item>
          <el-descriptions-item label="Description">{{ selectedTest.description }}</el-descriptions-item>
          <el-descriptions-item label="Comments">{{ selectedTest.comments || 'N/A' }}</el-descriptions-item>
        </el-descriptions>
        
        <div v-if="selectedTest.details && selectedTest.details.length" style="margin-top: 20px;">
          <h3>Test Parameters</h3>
          <el-table :data="selectedTest.details" style="width: 100%">
            <el-table-column prop="parameter" label="Parameter" />
            <el-table-column prop="value" label="Value" />
            <el-table-column prop="range" label="Normal Range" />
            <el-table-column prop="interpretation" label="Interpretation" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// Mock user info for development
const userInfo = ref({
  id: 'P001',
  name: 'John Doe',
  gender: 1,
  birthDate: '1980-05-15',
  phone: '123-456-7890',
  email: 'john@example.com',
  address: '123 Main St, Anytown, USA',
  avatar: ''
})

// Health tips
const healthTips = [
  'Stay hydrated by drinking at least 8 glasses of water daily.',
  'Aim for at least 30 minutes of moderate exercise most days of the week.',
  'Include a variety of fruits and vegetables in your daily diet.',
  'Get 7-9 hours of quality sleep each night for optimal health.',
  'Practice mindfulness or meditation to reduce stress levels.'
]

const healthTip = ref(healthTips[Math.floor(Math.random() * healthTips.length)])

// Mock next appointment
const nextAppointment = ref({
  id: 1,
  date: '2025-04-15',
  time: '10:30 AM',
  doctorName: 'Dr. Sarah Johnson',
  department: 'Cardiology'
})

// Mock upcoming appointments
const upcomingAppointments = ref([
  {
    id: 1,
    date: '2025-04-15',
    time: '10:30 AM',
    doctorName: 'Dr. Sarah Johnson',
    department: 'Cardiology',
    status: 'Confirmed'
  },
  {
    id: 2,
    date: '2025-04-22',
    time: '2:15 PM',
    doctorName: 'Dr. Michael Brown',
    department: 'Dermatology',
    status: 'Confirmed'
  },
  {
    id: 3,
    date: '2025-05-03',
    time: '9:00 AM',
    doctorName: 'Dr. Robert Williams',
    department: 'Neurology',
    status: 'Pending'
  }
])

// Mock prescriptions
const recentPrescriptions = ref([
  {
    id: 1,
    date: '2025-04-01',
    medication: 'Amoxicillin 500mg',
    dosage: '1 tablet 3 times daily',
    doctor: 'Dr. Sarah Johnson',
    instructions: 'Take with food',
    duration: '7 days',
    notes: 'Complete the entire course even if feeling better'
  },
  {
    id: 2,
    date: '2025-03-15',
    medication: 'Lisinopril 10mg',
    dosage: '1 tablet daily',
    doctor: 'Dr. Michael Brown',
    instructions: 'Take in the morning',
    duration: '30 days',
    notes: 'For blood pressure control'
  }
])

// Mock medical tests
const recentTests = ref([
  {
    id: 1,
    date: '2025-04-02',
    test: 'Complete Blood Count',
    result: 'Normal',
    doctor: 'Dr. Sarah Johnson',
    description: 'Routine blood test',
    comments: 'All parameters within normal range',
    details: [
      { parameter: 'WBC', value: '7.5 x 10^9/L', range: '4.0-11.0 x 10^9/L', interpretation: 'Normal' },
      { parameter: 'RBC', value: '5.0 x 10^12/L', range: '4.5-5.5 x 10^12/L', interpretation: 'Normal' },
      { parameter: 'Hemoglobin', value: '14.5 g/dL', range: '13.5-17.5 g/dL', interpretation: 'Normal' },
      { parameter: 'Platelets', value: '250 x 10^9/L', range: '150-450 x 10^9/L', interpretation: 'Normal' }
    ]
  },
  {
    id: 2,
    date: '2025-03-20',
    test: 'Lipid Profile',
    result: 'Abnormal',
    doctor: 'Dr. Michael Brown',
    description: 'Cholesterol test',
    comments: 'LDL cholesterol elevated',
    details: [
      { parameter: 'Total Cholesterol', value: '220 mg/dL', range: '< 200 mg/dL', interpretation: 'High' },
      { parameter: 'LDL Cholesterol', value: '150 mg/dL', range: '< 100 mg/dL', interpretation: 'High' },
      { parameter: 'HDL Cholesterol', value: '45 mg/dL', range: '> 40 mg/dL', interpretation: 'Normal' },
      { parameter: 'Triglycerides', value: '130 mg/dL', range: '< 150 mg/dL', interpretation: 'Normal' }
    ]
  }
])

// Mock doctors
const doctorOptions = ref([
  { id: 1, name: 'Dr. Sarah Johnson', department: 'Cardiology' },
  { id: 2, name: 'Dr. Michael Brown', department: 'Dermatology' },
  { id: 3, name: 'Dr. Robert Williams', department: 'Neurology' },
  { id: 4, name: 'Dr. Emily Davis', department: 'Orthopedics' },
  { id: 5, name: 'Dr. James Wilson', department: 'Pediatrics' },
  { id: 6, name: 'Dr. Jennifer Taylor', department: 'Psychiatry' }
])

// Mock time slots
const availableTimeSlots = ref([
  { label: '9:00 AM', value: '09:00', disabled: false },
  { label: '9:30 AM', value: '09:30', disabled: false },
  { label: '10:00 AM', value: '10:00', disabled: false },
  { label: '10:30 AM', value: '10:30', disabled: false },
  { label: '11:00 AM', value: '11:00', disabled: true },
  { label: '11:30 AM', value: '11:30', disabled: false },
  { label: '1:00 PM', value: '13:00', disabled: false },
  { label: '1:30 PM', value: '13:30', disabled: false },
  { label: '2:00 PM', value: '14:00', disabled: true },
  { label: '2:30 PM', value: '14:30', disabled: false },
  { label: '3:00 PM', value: '15:00', disabled: false },
  { label: '3:30 PM', value: '15:30', disabled: false },
  { label: '4:00 PM', value: '16:00', disabled: false }
])

// Dialog visibility and form data
const appointmentDialogVisible = ref(false)
const profileDialogVisible = ref(false)
const prescriptionDetailDialogVisible = ref(false)
const testDetailDialogVisible = ref(false)

const appointmentForm = ref({
  department: '',
  doctorId: null,
  date: '',
  time: '',
  reason: ''
})

const profileForm = ref({
  name: '',
  phone: '',
  email: '',
  address: ''
})

const selectedPrescription = ref({})
const selectedTest = ref({})

// Form rules
const appointmentRules = {
  department: [{ required: true, message: 'Please select a department', trigger: 'change' }],
  doctorId: [{ required: true, message: 'Please select a doctor', trigger: 'change' }],
  date: [{ required: true, message: 'Please select a date', trigger: 'change' }],
  time: [{ required: true, message: 'Please select a time slot', trigger: 'change' }],
  reason: [{ required: true, message: 'Please provide a reason for your visit', trigger: 'blur' }]
}

const profileRules = {
  name: [{ required: true, message: 'Please enter your name', trigger: 'blur' }],
  phone: [{ required: true, message: 'Please enter your phone number', trigger: 'blur' }],
  email: [{ required: true, message: 'Please enter your email', trigger: 'blur' }],
  address: [{ required: true, message: 'Please enter your address', trigger: 'blur' }]
}

onMounted(() => {
  // In a real app, you would fetch data from the API
  console.log('Patient dashboard mounted')
  
  // Initialize profile form with user data
  profileForm.value = {
    name: userInfo.value.name,
    phone: userInfo.value.phone,
    email: userInfo.value.email,
    address: userInfo.value.address
  }
})

// Utility functions
function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD')
}

function getStatusType(status) {
  if (status === 'Confirmed') return 'success'
  if (status === 'Pending') return 'warning'
  if (status === 'Cancelled') return 'danger'
  return 'info'
}

function getResultType(result) {
  if (result === 'Normal') return 'success'
  if (result === 'Abnormal') return 'warning'
  if (result === 'Critical') return 'danger'
  return 'info'
}

function disablePastDates(date) {
  return date < dayjs().subtract(1, 'day')
}

// Action handlers
function bookAppointment() {
  appointmentForm.value = {
    department: '',
    doctorId: null,
    date: '',
    time: '',
    reason: ''
  }
  appointmentDialogVisible.value = true
}

async function submitAppointment() {
  try {
    // In a real app, you would submit the appointment to the API
    console.log('Submitting appointment:', appointmentForm.value)
    
    // For demo purposes, add to upcoming appointments
    const doctor = doctorOptions.value.find(d => d.id === appointmentForm.value.doctorId)
    const timeSlot = availableTimeSlots.value.find(s => s.value === appointmentForm.value.time)
    
    upcomingAppointments.value.push({
      id: upcomingAppointments.value.length + 1,
      date: appointmentForm.value.date,
      time: timeSlot ? timeSlot.label : appointmentForm.value.time,
      doctorName: doctor ? doctor.name : 'Unknown Doctor',
      department: appointmentForm.value.department,
      status: 'Pending'
    })
    
    ElMessage.success('Appointment request submitted')
    appointmentDialogVisible.value = false
  } catch (error) {
    ElMessage.error('Failed to submit appointment')
  }
}

async function cancelAppointment(appointment) {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to cancel your appointment on ${formatDate(appointment.date)} at ${appointment.time}?`,
      'Cancel Appointment',
      {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }
    )
    
    // In a real app, you would call the API to cancel the appointment
    const index = upcomingAppointments.value.findIndex(a => a.id === appointment.id)
    if (index !== -1) {
      upcomingAppointments.value[index].status = 'Cancelled'
      ElMessage.success('Appointment cancelled successfully')
    }
  } catch (error) {
    // User cancelled the operation
  }
}

function rescheduleAppointment(appointment) {
  ElMessage.info('Reschedule functionality not implemented yet')
}

function editProfile() {
  profileDialogVisible.value = true
}

function saveProfile() {
  // In a real app, you would submit the profile to the API
  console.log('Saving profile:', profileForm.value)
  
  // Update local user info
  userInfo.value.name = profileForm.value.name
  userInfo.value.phone = profileForm.value.phone
  userInfo.value.email = profileForm.value.email
  userInfo.value.address = profileForm.value.address
  
  ElMessage.success('Profile updated successfully')
  profileDialogVisible.value = false
}

function viewMedicalRecords() {
  ElMessage.info('Medical records functionality not implemented yet')
}

function contactDoctor() {
  ElMessage.info('Contact doctor functionality not implemented yet')
}

function viewPrescriptions() {
  ElMessage.info('Prescriptions view functionality not implemented yet')
}

function setReminders() {
  ElMessage.info('Medication reminders functionality not implemented yet')
}

function requestRecords() {
  ElMessage.info('Records request functionality not implemented yet')
}

function viewPrescriptionDetails(prescription) {
  selectedPrescription.value = prescription
  prescriptionDetailDialogVisible.value = true
}

function viewTestDetails(test) {
  selectedTest.value = test
  testDetailDialogVisible.value = true
}
</script>

<style scoped>
.patient-dashboard {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-content {
  padding: 10px 0;
}

.health-tip {
  font-style: italic;
  color: #666;
  margin: 15px 0;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.upcoming-appointments-card, 
.profile-card, 
.quick-actions-card, 
.recent-prescriptions-card, 
.recent-tests-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  padding: 10px 0;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.profile-details {
  margin-top: 10px;
}

.quick-actions-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style> 